<template>
  <div class="personal">
    <el-card>
      <div slot="header"><span>个人中心</span></div>
      <div>管理员ID:{{ userInfo.id }}</div>
      <el-divider></el-divider>
      <div>账号:{{ userInfo.account }}</div>
      <el-divider></el-divider>
      <div>用户组:{{ userInfo.userGroup }}</div>
      <el-divider></el-divider>
      <div>创建时间:{{ userInfo.ctime | formatYMD }}</div>
      <el-divider></el-divider>
      <div>
        <el-upload class="avatar-uploader" :action="`${API}/users/avatar_upload`" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="userInfo.imgUrl" :src="userInfo.imgUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
    </el-card>
  </div>
</template>

<script>
//赋值函数语法 解构数据
import { mapState } from 'vuex'
import { updateUserAvatarReq } from '@/api/user'
export default {
  computed: {
    ...mapState('user', ['userInfo']),
  },
  data() {
    return {
      //服务器地址
      API: 'http://sell.h5.itsource.cn:8087',
    }
  },
  methods: {
    //上传成功触发的函数
    async handleAvatarSuccess(res) {
      //解构数据
      let { code, msg, imgUrl } = res
      //判断
      if (code === 0) {
        //发请求修改头像
        let res2 = await updateUserAvatarReq({
          imgUrl,
        })
        //解构数据
        let { code, msg } = res2.data
        //判断
        if (code === 0) {
          //拉取用户信息
          this.$store.dispatch('user/A_getUserInfo')
        }
      }
    },
    //约束上传文件类型 & 上传文件大小
    beforeAvatarUpload(file) {
      const isJPG = /(png|jpeg)/.test(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是PNG JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
  },
}
</script>

<style lang="scss" scoped>

.personal{
  margin: 20px 0px 0px 20px;
}
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  line-height: 90px;
  text-align: center;
}

.avatar {
  width: 90px;
  height: 90px;
  display: block;
}
</style>
